package com.distribution.common.web.handler;

import com.distribution.common.util.JwtUtils;
import com.distribution.common.web.auth.LoginToken;
import com.distribution.common.web.response.ResponseResult;
import com.distribution.common.web.response.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author test
 * @date 2022年01月04日 11:42
 */

@Component
public class LoginAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //可以根据业务需求进行处理， 我们这里只返回两个token
        //access token
        String accessToken = jwtUtils.createToken(userDetails.getUsername());
        String refreshToken = jwtUtils.refreshToken(accessToken);
        LoginToken loginToken = LoginToken.builder().accessToken(accessToken)
                                        .refreshToken(refreshToken)
                                  .build();
        renderToken(httpServletResponse,loginToken);
    }

    /**
     * 渲染返回token数据， 因为前端页面接受都是ResponseEntity对象
     */
    private void renderToken(HttpServletResponse response,LoginToken loginToken) throws IOException {
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(HttpStatus.OK.value());
        responseResult.setMessage("login success");
        responseResult.setData(loginToken);
        ResponseUtils.send(response,responseResult);
    }
}
